<template>
  <div class="p-2">
    <div ref="chartDom" style="width: 100%; height: 600px;"></div>
  </div>
</template>

<script setup lang="ts">
import { defineProps, onMounted, ref, watch, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import { listMarket } from '@/api/market/market';  // 引入 API 函数

// 添加 props 定义
const props = defineProps({
  symbol: {
    type: String,
    required: true
  }
});

const chartDom = ref<HTMLElement | null>(null);
let myChart: echarts.ECharts | null = null;
let resizeHandler: (() => void) | null = null;

const chartData = ref({
  dates: [] as string[],
  klineData: [] as number[][],
  volumeData: [] as number[],
  ma5: [] as (string | number)[],
  ma10: [] as (string | number)[],
  ma20: [] as (string | number)[]
});

// 计算移动平均线
function calculateMA(dayCount: number, closePrices: number[]) {
  const result: (string | number)[] = [];
  for (let i = 0; i < closePrices.length; i++) {
    if (i < dayCount - 1) {
      result.push('-');
      continue;
    }
    const sum = closePrices.slice(i - dayCount + 1, i + 1).reduce((acc, val) => acc + val, 0);
    result.push((sum / dayCount).toFixed(2));
  }
  return result;
}

// 数据请求和处理
const fetchData = async () => {
  try {
    const response = await listMarket({
      symbol: props.symbol,
      pageSize: 1000,
      pageNum: 1
    });

    // 处理数据并更新 chartData
    const data = response.rows;

    const dates = data.map(item => item.time.split(' ')[0]);
    const klineData = data.map(item => [
      item.open,
      item.preclose,
      item.low,
      item.high
    ]);
    const volumeData = data.map(item => item.volume);
    const closePrices = klineData.map(item => item[1]);
    const ma5 = calculateMA(5, closePrices);
    const ma10 = calculateMA(10, closePrices);
    const ma20 = calculateMA(20, closePrices);

    chartData.value = {
      dates,
      klineData,
      volumeData,
      ma5,
      ma10,
      ma20
    };

    renderChart(); // 渲染图表
  } catch (error) {
    console.error('Error fetching data:', error);
  }
};

// 渲染图表
const renderChart = () => {
  if (!chartDom.value) {
    console.warn('chartDom is not available');
    return;
  }
  // 销毁旧实例
  if (myChart) {
    myChart.dispose();
  }
  myChart = echarts.init(chartDom.value);

  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const candlestickData = params.find(param => param.seriesType === 'candlestick');
        if (!candlestickData || !candlestickData.value) return '';
        // 对应截图里的 open、close、lowest、highest 命名
        const [open, close, lowest, highest] = candlestickData.value; 
        // 获取 MA 数据
        const ma5 = chartData.value.ma5[candlestickData.dataIndex];
        const ma10 = chartData.value.ma10[candlestickData.dataIndex];
        const ma20 = chartData.value.ma20[candlestickData.dataIndex];
        // 获取成交量数据
        const volume = chartData.value.volumeData[candlestickData.dataIndex];
        return `
          <div>${candlestickData.name}</div>
          <div style="margin: 4px 0;">
            <span style="display: inline-block;width: 8px;height: 8px;background-color: red;border-radius: 50%;margin-right: 4px;"></span>日K
          </div>
          <div>open: ${open}</div>
          <div>close: ${close}</div>
          <div>lowest: ${lowest}</div>
          <div>highest: ${highest}</div>
          <div style="margin: 4px 0;">
            <span style="display: inline-block;width: 8px;height: 8px;background-color: brown;border-radius: 50%;margin-right: 4px;"></span>MA5: ${ma5}
          </div>
          <div>
            <span style="display: inline-block;width: 8px;height: 8px;background-color: black;border-radius: 50%;margin-right: 4px;"></span>MA10: ${ma10}
          </div>
          <div>
            <span style="display: inline-block;width: 8px;height: 8px;background-color: #0088cc;border-radius: 50%;margin-right: 4px;"></span>MA20: ${ma20}
          </div>
          <div style="margin: 4px 0;">
            <span style="display: inline-block;width: 8px;height: 8px;background-color: green;border-radius: 50%;margin-right: 4px;"></span>Volume: ${volume}
          </div>
        `;
      }
    },
    xAxis: [
      {
        type: 'category',
        data: chartData.value.dates
      },
      {
        type: 'category',
        gridIndex: 1,
        data: chartData.value.dates
      }
    ],
    yAxis: [
      {
        scale: true,
        splitNumber: 2
      },
      {
        scale: true,
        gridIndex: 1,
        splitLine: { show: false }
      }
    ],
    grid: [
      {
        left: 20,
        right: 20,
        top: 110,
        height: 120
      },
      {
        left: 20,
        right: 20,
        top: 260,
        height: 40
      }
    ],
    series: [
      {
        name: '成交量',
        type: 'bar',
        xAxisIndex: 1,
        yAxisIndex: 1,
        data: chartData.value.volumeData
      },
      {
        type: 'candlestick',
        name: '日K',
        data: chartData.value.klineData
      },
      {
        name: 'MA5',
        type: 'line',
        smooth: true,
        showSymbol: false,
        data: chartData.value.ma5
      },
      {
        name: 'MA10',
        type: 'line',
        smooth: true,
        showSymbol: false,
        data: chartData.value.ma10
      },
      {
        name: 'MA20',
        type: 'line',
        smooth: true,
        showSymbol: false,
        data: chartData.value.ma20
      }
    ]
  };

  myChart.setOption(option);

  // 绑定 resize 事件（统一管理）
  if (resizeHandler) {
    window.removeEventListener('resize', resizeHandler);
  }
  resizeHandler = () => {
    myChart?.resize();
  };
  window.addEventListener('resize', resizeHandler);
};

// 添加 watch 监听 symbol 变化
watch(
  () => props.symbol,
  (newVal) => {
    fetchData();
  }
);

// 初始化时获取数据
onMounted(async () => {
  await fetchData();
});

// 清理逻辑
onUnmounted(() => {
  if (myChart) {
    myChart.dispose();
  }
  if (resizeHandler) {
    window.removeEventListener('resize', resizeHandler);
  }
});
</script>

<style scoped>
/* 可以添加一些样式 */
</style>
